package exemples;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.math.*;

public class Exo1 extends JFrame implements ActionListener,KeyListener{

	JTextField tf1;
	JTextField tf2;
	boolean sens = true;
	
	public Exo1(){
		setSize(200,120);
		setTitle("Convertisseur Euros/Francs");
		
		JPanel pn = new JPanel();
		
		Box box1 = new Box(BoxLayout.X_AXIS);
		Box box2 = new Box(BoxLayout.X_AXIS);
		Box box3 = new Box(BoxLayout.X_AXIS);
		Box box4 = new Box(BoxLayout.Y_AXIS);
		
		JLabel lb1 = new JLabel("Francs");
		tf1 = new JTextField("");
		tf1.addKeyListener(this);
		
		JLabel lb2 = new JLabel("Euros");
		tf2 = new JTextField("");
		tf2.addKeyListener(this);
		
		JButton bouton = new JButton("Convertir");
		bouton.addActionListener(this);
		
		box1.add(lb1);
		box1.add(tf1);
		box2.add(lb2);
		box2.add(tf2);
		box3.add(bouton);
		box4.add(box1);
		box4.add(box2);
		box4.add(box3);
		
		pn.add(box4);
		
		this.getContentPane().add(pn);
	}
	
	public double convertir(double val){
		double retour;
		if(sens)
			retour = val/6.55957;
		else
			retour = val*6.55957;
		retour = retour*100;
		retour = Math.round(retour);
		retour = retour/100;
		return retour;
	}
	
	public void actionPerformed(ActionEvent e){
		if(e.getSource()instanceof JButton)
		{
			if(sens)
			{
				try{
					tf2.setText(String.valueOf(convertir(Double.parseDouble(tf1.getText()))));
				}catch(NumberFormatException ex){
					JOptionPane.showMessageDialog(this,"Entrez un nombre correct !");
				}
			}else{
				try{
					tf1.setText(String.valueOf(convertir(Double.parseDouble(tf2.getText()))));
				}catch(NumberFormatException ex){
					JOptionPane.showMessageDialog(this,"Entrez un nombre correct !");
				}
			}
		}
	}
	
	public void keyPressed(KeyEvent e){
		if(e.getSource()==tf1)
			sens = true;
		else
			sens = false;
		
		if(e.getKeyChar()== KeyEvent.VK_ENTER)
		{
			if(sens)
			{
				try{
					tf2.setText(String.valueOf(convertir(Double.parseDouble(tf1.getText()))));
				}catch(NumberFormatException ex){
					JOptionPane.showMessageDialog(this,"Entrez un nombre correct !");
				}
			}else{
				try{
					this.tf1.setText(String.valueOf(convertir(Double.parseDouble(tf2.getText()))));
				}catch(NumberFormatException ex){
					JOptionPane.showMessageDialog(this,"Entrez un nombre correct !");
				}
			}
		}
	}
	public void keyReleased(KeyEvent e){}
	public void keyTyped(KeyEvent e){}
	
	
	public static void main(String[] args){
		Exo1 test = new Exo1();
		test.setVisible(true);
	}
	
}
